package com.letu.aopcache.manager;

import com.alibaba.fastjson.JSON;
import com.letu.annotation.annotation.cache.Cache;
import com.letu.aopcache.aop.CacheAopProxyChain;
import com.letu.aopcache.clone.ICloner;
import com.letu.aopcache.model.AutoLoadConfig;
import com.letu.aopcache.model.CacheKeyTO;
import com.letu.aopcache.model.MethodMsg;
import com.letu.aopcache.parser.AbstractScriptParser;
import com.letu.aopcache.util.CacheUtil;
import com.letu.core.context.ContextUtil;
import com.letu.core.context.StaticContextUtil;
import com.letu.core.utils.HeaderUtil;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Method;
import java.util.Map;

/**
 * 瓶装 接口信息
 */
@Slf4j
public class MethodMsgManager {
    /**
     * 组装方法信息
     *
     * @param pjp
     * @param cache
     * @return
     */
    public MethodMsg assembleMethodMsg(ICloner cloner, CacheAopProxyChain pjp, Cache cache) {
        Object target = pjp.getTarget();
        Method method = pjp.getMethod();

//        Object[] arguments = pjp.getArgs();
        // 进行深度复制(因为是异步执行，防止外部修改参数值)
        Object[] arguments = new Object[0];
        try {
            arguments = (Object[]) cloner.deepCloneArgs(pjp.getArgs());
        } catch (Exception e) {
            arguments = pjp.getArgs();
        }
        MethodMsg methodMsg = new MethodMsg();
        methodMsg.setMethodName(method.getName());
        methodMsg.setArgs(arguments);
        //组装请求头信息
        Map<String, Object> map = HeaderUtil.getHeaderMap();
        map.put("profileActive", StaticContextUtil.getProfilesActive());
        map.remove("trace");
        methodMsg.setHeader(map);
        methodMsg.setClassName(target.getClass().getName());
//        methodMsg.setClassName(method.getDeclaringClass().getName());
        methodMsg.setReturnType(method.getReturnType());
        methodMsg.setTarget(target);
        try {
            methodMsg.setCacheKeyBuilder(CacheUtil.getCacheKeyInvok(methodMsg));
        } catch (Exception e) {
            log.info("NoSuchMethodException: getCacheKeyBuilder{}",e.getMessage());
//            e.printStackTrace();
        }
        return methodMsg;
    }


}
